import 'dart:async';
import 'dart:io';
import 'package:city_pickers/city_pickers.dart';
import 'package:common_utils/common_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:part_time_job_pro/common/index.dart';
import 'package:part_time_job_pro/pages/register/state.dart';

class RegisterLogic extends BaseController {
  final RegisterState state = RegisterState();
  //定时器
  late Timer _timer;

  ///输入监听
  late TextEditingController mobileTextEditController;
  late TextEditingController companyTextEditController;
  late TextEditingController contactTextEditController;
  late TextEditingController verifyCodeTextFieldController;
  late TextEditingController passwordTextFieldController;

  ///监听是否正在输入数据
  late FocusNode mobileFocusNode;
  late FocusNode contactFocusNode;
  late FocusNode companyFocusNode;
  late FocusNode verifyCodeFocusNode;
  late FocusNode passwordFocusNode;

  //初始化
  @override
  void onInit() {
    initFocusNode();
    super.onInit();
  }

  //注销函数
  @override
  void onClose() {
    contactTextEditController.dispose();
    companyTextEditController.dispose();
    mobileTextEditController.dispose();
    passwordTextFieldController.dispose();
    verifyCodeTextFieldController.dispose();
    super.onClose();
  }

  ///监听是否在输入密码或验证码
  initFocusNode() {
    companyTextEditController = TextEditingController();
    contactTextEditController = TextEditingController();
    mobileTextEditController = TextEditingController();
    verifyCodeTextFieldController = TextEditingController();
    passwordTextFieldController = TextEditingController();

    companyFocusNode = FocusNode();
    contactFocusNode = FocusNode();
    mobileFocusNode = FocusNode();
    verifyCodeFocusNode = FocusNode();
    passwordFocusNode = FocusNode();

    companyFocusNode.addListener(() {
      if (companyFocusNode.hasFocus) {
        state.isInputPassword = false;
      } else {
        state.isInputPassword = true;
      }
      update();
    });
    contactFocusNode.addListener(() {
      if (contactFocusNode.hasFocus) {
        state.isInputPassword = false;
      } else {
        state.isInputPassword = true;
      }
      update();
    });
    mobileFocusNode.addListener(() {
      if (mobileFocusNode.hasFocus) {
        state.isInputPassword = false;
      } else {
        state.isInputPassword = true;
      }
      update();
    });

    passwordFocusNode.addListener(() {
      if (passwordFocusNode.hasFocus) {
        state.isInputPassword = true;
      } else {
        state.isInputPassword = false;
      }
      update();
    });
    verifyCodeFocusNode.addListener(() {
      if (verifyCodeFocusNode.hasFocus) {
        state.isInputPassword = true;
      } else {
        state.isInputPassword = false;
      }
      update();
    });
  }

  ///是否同意协议
  changeIsAgree() {
    state.isAgreement = !state.isAgreement;
    update();
  }

  ///监听用户名称输入
  updateCompanyName(String text) {
    state.companyName = text;
    update();
  }

  //清空账号输入
  clearCompanyName() {
    state.companyName = '';
    companyTextEditController.clear();
    companyFocusNode.unfocus();
    update();
  }

  ///监听联系人输入
  updateContactName(String text) {
    state.contactName = text;
    update();
  }

  //清空账号输入
  clearContactName() {
    state.contactName = '';
    contactTextEditController.clear();
    contactFocusNode.unfocus();
    update();
  }

  ///监听电话输入
  updateTel(String text) {
    state.mobileText = text;
    update();
  }

  //清空电话输入
  clearTel() {
    state.mobileText = '';
    mobileTextEditController.clear();
    mobileFocusNode.unfocus();
    update();
  }

  ///监听密码输入
  updatePassword(String text) {
    state.passwordText = text;
    update();
  }

  //清空密码输入
  clearPassword() {
    state.passwordText = '';
    passwordTextFieldController.clear();
    passwordFocusNode.unfocus();
    update();
  }

  ///监听验证码输入
  updateVerifyText(String text) {
    state.verifyText = text;
    update();
  }

  //清空验证码输入
  clearVerifyCode() {
    state.verifyText = '';
    verifyCodeTextFieldController.clear();
    verifyCodeFocusNode.unfocus();
    update();
  }

  //修改密码隐藏
  updateIsObscure() {
    state.isObscure = !state.isObscure;
    update();
  }

  //选择地区
  showCitySelector(context) async {
    Result? result2;
    if (Platform.isAndroid) {
      result2 = await CityPickers.showFullPageCityPicker(
          context: context, locationCode: state.locationCode);
    } else {
      result2 = await CityPickers.showCityPicker(
          context: context, locationCode: state.locationCode);
    }

    if (result2 != null) {
      state.countryText =
          "${result2.provinceName} ${result2.cityName} ${result2.areaName}";
      state.locationCode =
          result2.areaId == null ? result2.cityId! : result2.areaId!;
    } else {
      state.countryText = "";
      state.locationCode = "";
    }
    update();
    LogUtil.e(result2);
  }

  startTimer(int seconds) {
    //设置 1 秒回调一次
    const period = Duration(seconds: 1);
    _timer = Timer.periodic(period, (timer) {
      //秒数减一，因为一秒回调一次
      seconds--;
      state.codeSeconds = seconds;
      if (seconds == 0) {
        //倒计时秒数为0，取消定时器
        cancelTimer();
      }
      update();
    });
  }

  //清除定时器
  cancelTimer() {
    _timer.cancel();
  }

  ///注册账号
  registerAccount() {
    if (state.companyName.isEmpty) {
      EasyLoading.showToast("请输入公司名称");
      return;
    }

    if (state.contactName.isEmpty) {
      EasyLoading.showToast("请输入联系人称呼");
      return;
    }

    if (state.countryText.isEmpty) {
      EasyLoading.showToast("请选择所属地区");
      return;
    }

    if (state.mobileText.isEmpty) {
      EasyLoading.showToast("请输入联系电话");
      return;
    }

    if (state.passwordText.isEmpty) {
      EasyLoading.showToast("请输入登录密码");
      return;
    }

    if (state.verifyText.isEmpty) {
      EasyLoading.showToast("请输入短信验证码");
      return;
    }

    if (!state.isAgreement) {
      EasyLoading.showToast("您还没有同意《用户协议》");
      return;
    }

    if (!CommonUtil.validPhone(state.mobileText)) {
      EasyLoading.showToast("联系电话格式错误!");
      return;
    }

    //处理参数、密码加密
    Map<String, dynamic> params = {
      "username": state.companyName,
      "contact": state.contactName,
      "password": CommonUtil.generateMd5(state.passwordText),
      "mobile": state.mobileText,
      "address": state.countryText,
      "smscode": state.verifyText
    };

    UserApi().registerAccount((data) {
      if (data is LoginUser) {
        EasyLoading.showToast("注册成功,请重新登陆!");
        //进入登录页面
        Future.delayed(const Duration(seconds: 1)).whenComplete(() {
          Get.offAndToNamed(AppRoutes.userLogin);
        });
      } else {
        clearVerifyCode();
        var resultMsg = data[ResponesCode.msgTag];
        EasyLoading.showToast("注册失败: $resultMsg");
      }
    }, params);
  }

  ///发送短信验证码
  getSmsCode() {
    //先清除输入框
    clearVerifyCode();
    if (state.mobileText.isEmpty) {
      EasyLoading.showToast("请输入联系电话");
      return;
    }
    //先进行验证 然后发送短信验证码
    SmsApi().sendSmsCode((data) {
      int resultCode = data[ResponesCode.codeTag];
      var resultMsg = data[ResponesCode.msgTag];
      if (resultCode == ResponesCode.successCode) {
        var resultData = data[ResponesCode.dataTag];
        EasyLoading.showToast("发送成功!");
        startTimer(resultData);
      } else {
        EasyLoading.showToast("发送失败: $resultMsg");
      }
    }, state.mobileText, type: "1");
  }
}
